import { createApp } from 'vue'
import Toast from '../components/common/Toast.vue'

class ToastService {
  private container: HTMLDivElement | null = null

  constructor() {
    // 初始化Toast容器
    this.initContainer()
  }

  private initContainer() {
    if (!this.container) {
      this.container = document.createElement('div')
      this.container.className = 'toast-container'
      document.body.appendChild(this.container)
    }
  }

  private showToast(message: string, type: 'success' | 'error' | 'info' = 'info', duration: number = 3000) {
    if (!this.container) {
      this.initContainer()
    }

    // 创建新的Toast实例
    const toastApp = createApp(Toast, {
      message,
      type,
      duration
    })

    // 创建挂载节点
    const toastMount = document.createElement('div')
    if (this.container) {
      this.container.appendChild(toastMount)
    }

    // 挂载Toast组件
    toastApp.mount(toastMount)

    // 定时移除组件
    setTimeout(() => {
      toastApp.unmount()
      if (this.container && toastMount.parentNode) {
        this.container.removeChild(toastMount)
      }
    }, duration + 300) // 额外加300ms用于动画效果
  }

  // 成功消息
  success(message: string, duration?: number) {
    this.showToast(message, 'success', duration)
  }

  // 错误消息
  error(message: string, duration?: number) {
    this.showToast(message, 'error', duration)
  }

  // 信息消息
  info(message: string, duration?: number) {
    this.showToast(message, 'info', duration)
  }
}

// 创建单例实例
const toastService = new ToastService()

export default toastService